package com.javastudy.liuhouse.lambda.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class GroupStream {
    public static void main(String[] args) {
        List<StudentInfo> students = Arrays.asList(
                new StudentInfo(1, 1, "Alice", 85),
                new StudentInfo(1, 2, "Bob", 90),
                new StudentInfo(2, 1, "Charlie", 78),
                new StudentInfo(2, 2, "David", 92));
//        System.out.println(students);

        //按照年级分组
//        Map<Integer, List<StudentInfo>> studentByGrade = students.stream().collect(Collectors.groupingBy(StudentInfo::getGradeId));
////        System.out.println(studentByGrade);
//        //输出结果
//        studentByGrade.forEach((gradeId , studentInfoList) -> {
//            System.out.println("Grade Id: " + gradeId + ":");
//            studentInfoList.forEach(student -> System.out.println(student));
//        });

        //按照班级分组
//        Map<Integer, List<StudentInfo>> studentsByClass = students.stream().collect(Collectors.groupingBy(StudentInfo::getClassId));
//        //输出结果
//        studentsByClass.forEach((classId , studentList) -> {
//            System.out.println("Class: " + classId);
//            studentList.forEach(studentInfo -> System.out.println(studentInfo));
//        });

        //3.按照年级和班级两级分组
//        Map<Integer, Map<Integer, List<StudentInfo>>> studentsByGradeAndClass = students.stream().collect(Collectors.groupingBy(StudentInfo::getGradeId, Collectors.groupingBy(StudentInfo::getClassId)));
//        //输出结果
//        studentsByGradeAndClass.forEach((gradeId , classMap) -> {
//            System.out.println("Grade Id: " + gradeId);
//            classMap.forEach((classId , studentList) -> {
//                System.out.println("Class " + classId + ":");
//                studentList.forEach(student -> {
//                    System.out.println(student);
//                });
//            });
//        });


        //按照年级分组,并计算每个年级的平均分
        Map<Integer, Double> averageScoreByGrade = students.stream()
                .collect(Collectors.groupingBy(StudentInfo::getGradeId, Collectors.averagingInt(StudentInfo::getScore)));
        //输出结果
        averageScoreByGrade.forEach((gradeId , avgScore) -> {
            System.out.println("Grade  " + gradeId + "Average Score" + avgScore);
        });


    }
}
